//
//  ViolationMgr.m
//  carcareIOS
//
//  Created by 王然 on 16/8/3.
//  Copyright © 2016年 chezheng. All rights reserved.
//

#import "ViolationCityMgr.h"
#import "CacheMgr.h"
#import "CalendarMgr.h"
#import "NetViolations.h"
#import "VioCityModel.h"

#define VIOLATION_CITY_FILE @"VIOLATION_CITY_FILE"
#define K_FILE_DATE @"K_FILE_DATE"
#define K_FILE_INFO @"K_FILE_INFO"

NSString * const VIOLATION_CITY_UPDATE = @"VIOLATION_CITY_UPDATE";

@implementation ViolationCityMgr
IMP_SINGLETON
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(instancetype)init{
    self = [super init];
    if (self) {
        [self loadCity];
//        [self updateCarModelsFinish:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleMemoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    }
    return self;
}
-(void)handleMemoryWarning{
    self.provinceModels = nil;
    self.paramKeys = nil;
}
-(NSArray *)provinceModels{
    if (!_provinceModels) {
        [self loadCity];
    }
    return _provinceModels;
}
-(NSDictionary *)paramKeys{
    if (!_paramKeys) {
        [self loadCity];
    }
    return _paramKeys;
}
#pragma mark - city

-(NSArray *)subCityModelsWithSubCitys:(NSArray *)citys{
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:citys.count];
    [citys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        VioCityModel *model = [[VioCityModel alloc] initWithDic:obj];
        [arr addObject:model];
    }];
    return [arr copy];
}

-(void)loadCity{
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:[CacheMgr nonTmpCachePathWithName:VIOLATION_CITY_FILE]];
    if (dic &&
        [dic[K_FILE_DATE] isEqualToString:CALENDARMGR.currentDay] &&
        dic[K_FILE_INFO]) {
        [self dealWithCityDic:dic[K_FILE_INFO]];
    }else{
        [[NetViolations violationCityList] requestSuccess:^(id JSON) {
            NSDictionary *tmp = JSON[@"info"];
            if (tmp) {
                NSDictionary *write = @{K_FILE_DATE : CALENDARMGR.currentDay, K_FILE_INFO : tmp};
                [write writeToFile:[CacheMgr nonTmpCachePathWithName:VIOLATION_CITY_FILE] atomically:NO];
                [self dealWithCityDic:tmp];
            }
        }];
    }
}
-(void)dealWithCityDic:(NSDictionary *)dic{
    self.paramKeys = dic[@"config"];
    NSArray *provinces = dic[@"list"];
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:provinces.count];
    [provinces enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        VioCityModel *model = [[VioCityModel alloc] initWithDic:obj];
        [arr addObject:model];
    }];
    self.provinceModels = arr;
    [[NSNotificationCenter defaultCenter] postNotificationName:VIOLATION_CITY_UPDATE object:nil];
}

@end
